

import {Toast } from '@ant-design/react-native'
global.API_ROOT = 'http://localhost:8080/'   //服务器


//进行网络请求的方法
function request(address,body,method,isFile,completionBlock) {
  
  var fullUrl = (address.indexOf(API_ROOT) === -1) ? API_ROOT + address : address  
  //判断是否是上传文件
  // let format =  isFile ? 'multipart/form-data':'application/x-www-form-urlencoded'
  let format =  isFile ? 'multipart/form-data':'application/json'

    var headers = {
    'Content-Type': format,
  }
  // var headers = {
  //   'Accept': 'application/json',
  //   'Content-Type': 'multipart/form-data',
  // };

  let Json = {
    method,
    headers,
  };

  //如果请求方式为 “POST”
  if (method === "POST") {
    Json = Object.assign({},Json,{
      body: isFile ? body : JSON.stringify(body)
    })
  }
  console.log('\n%c网络请求url:','color:blue',fullUrl,'\n网络请求body:',Json.body,'\n headers:',Json.headers);
  const _fetch = (requestPromise,timeout=5000) =>{
    let timeoutAction = null;
    const timerPromise = new Promise(function(resolve, reject) {
      timeoutAction = () =>{
        reject('808080')
      }
    });
    setTimeout(()=>{
      timeoutAction()
    },timeout)
    return Promise.race([requestPromise,timerPromise]);
  }
  const myFetch = fetch(fullUrl,Json)

  new Promise(function(resolve, reject) {
    _fetch(myFetch,8000)
    .then(response =>{
      
      return response.json();
    })
    .then(result =>{
      console.log("api里面网络库返回参数:",result);

      let { data,code,msg } = result; 
      if (result.code === 200) {
        completionBlock(true,{
          code:200,
          msg:msg || '请求成功',
          data
        })
      }  else {
          completionBlock(false,{
          code:code,
          msg:msg || '不知道的错误信息',
          data
        })
      }   
    })
    .catch(error=>{
      console.log("(api文件fetch请求走catch:)错误信息:",error);
      completionBlock(false,{
        message:error==='808080'?'请求超时':'请求失败',
        code:error==='808080'?'808080':'808081'
      })
    })
  });
}

export const CALL_API = 'abc'

  export default store => next => action =>{
    const callAPI = action[CALL_API]
    if (typeof callAPI === 'undefined') {
      return next(action)
    }
    let {
      address,
      body,
      method,
      isFile,
      type,
      exit
    } = callAPI;

    if (!method) {
      throw new Error('你没有定义method')
    }

    if (typeof address !== 'string') {
      throw new Error('URL不是字符串')
    }

    function actionWith(data) {
      const finalAction = Object.assign({},action,data)
      delete finalAction[CALL_API]
      return finalAction
    }
    
    next(actionWith({
      type,
      exit,
      body
    }))   
    
    request(address,body,method,isFile,function (isSuccess,response) {
      if (isSuccess) {
        next(actionWith({
          exit,
          body,        
          response,
          type:address + 'Success'
        }))
      }else {
        next(actionWith({
          exit,
          body,
          response,
          type:address + 'Failure'
        }))
      }
    })
  }
